package com.shuqi.activity;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shuqi.activity.adapter.PurchaseHistoryAdapter;
import com.shuqi.activity.adapter.PurchaseHistoryAdapter.onPurchaseHistoryAdapterListener;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.MyListFooter;
import com.shuqi.activity.viewport.MyListFooter.MyFooterListener;
import com.shuqi.common.ControlHandler;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.MainController;
import com.shuqi.controller.PurchaseHistoryController;
import com.shuqi.controller.R;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.BuyRecordInfo;
import com.shuqi.model.bean.BuyRecordsInfo;
import com.shuqi.model.net.listener.HttpRequestErrListener;

/**
 * 购买记录
 * 
 * @author zhuchen
 * 
 */
public class PurchaseHistoryActivity extends ActivityBase implements IEventListener,
        OnClickListener, HttpRequestErrListener, OnItemClickListener,
        onPurchaseHistoryAdapterListener {

    private final int INIT = EventTypeConstants.BASE;
    private final int INITSUCCESS = INIT + 1;
    private final int SHOW404 = INITSUCCESS + 1;
    private final int LOADMORE_ERROR = SHOW404 + 1;
    private CommonTitle mTitle;
    private PurchaseHistoryController controller;
    private int totalPage; // 总页数
    private int pageIndex = 1;// 请求页
    private PurchaseHistoryAdapter adapter;
    private ListView mActPurchaseHistoryListview;
    private RelativeLayout act_purchasehistory_null;// 无购买书籍
    private BuyRecordsInfo buyRecordsInfo;
    private TextView purchasehistory_goshucheng;

    private List<BuyRecordInfo> mBuyRecordInfoListData = null;
    // 加载控制
    private LinearLayout loading;
    private LinearLayout err404;

    /** 加载更多footer */
    private MyListFooter mListFooter;

    private ControlHandler handler = new ControlHandler(this) {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case INIT:
                    activityLogicForward();
                    setAllOnListener();
                    break;
                case INITSUCCESS:
                    activityInitData();
                    break;
                case SHOW404:
                    show404();
                    break;
                case LOADMORE_ERROR:
                    loading.setVisibility(View.GONE);
                    mListFooter.loadingError();
                    break;
                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        controller =
                (PurchaseHistoryController) MainController.getMainManagerInstance()
                        .createController(MainController.CONTROLLER_ID_PURCHASEHISTORY, this);
        controller.addEventListener(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_purchasehistory);
        handler.sendEmptyMessage(INIT);
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                buyRecordsInfo = (BuyRecordsInfo) data;
                handler.sendEmptyMessage(INITSUCCESS);
                break;
            default:
                if (mBuyRecordInfoListData == null) {
                    handler.sendEmptyMessage(SHOW404);
                } else {
                    handler.sendEmptyMessage(LOADMORE_ERROR);
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.purchasehistory_goshucheng:
                MainActivityGroup.show(this, MainActivityGroup.PAGE_POSITION_BOOKSQUARE, true);
                break;
            case R.id.retry:
//                if (!Util.isNetworkConnected(this)) {
//                    return;
//                }
//                this.controller.handle(0, this.pageIndex);
//                loading.setVisibility(View.VISIBLE);
                
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        controller.handle(0, pageIndex);
                        loading.setVisibility(View.VISIBLE);

                    }
                });
                break;
            default:
                break;
        }

    }

    @Override
    protected void onDestroy() {
        controller.onDestroy();
        super.onDestroy();
    }

    @Override
    public void activityLogicForward() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        err404 = (LinearLayout) findViewById(R.id.include_error);
        loading = (LinearLayout) findViewById(R.id.include_loading);
        act_purchasehistory_null = (RelativeLayout) findViewById(R.id.act_purchasehistory_null);
        mActPurchaseHistoryListview = (ListView) findViewById(R.id.act_purchasehistory_list);
        purchasehistory_goshucheng = (TextView) findViewById(R.id.purchasehistory_goshucheng);
    }

    /** 设置监听事件 */
    private void setAllOnListener() {
        mTitle.setLeftClickListener(this);
        purchasehistory_goshucheng.setOnClickListener(this);
        findViewById(R.id.retry).setOnClickListener(this);

        MyFooterListener listener = new MyFooterListener() {

            @Override
            public void reload() {
                requestAppList();
            }

            @Override
            public void loadNext() {
                requestAppList();
            }

            @Override
            public boolean hasNext() {
                if (mBuyRecordInfoListData == null || mBuyRecordInfoListData.size() == 0) {
                    return false;
                }
                if (totalPage >= pageIndex) {
                    return true;
                } else {
                    return false;
                }
            }
        };
        mListFooter = new MyListFooter(this, listener);
        mActPurchaseHistoryListview.addFooterView(mListFooter);
        mActPurchaseHistoryListview.setOnItemClickListener(this);

        requestAppList();
        loading.setVisibility(View.VISIBLE);
    }

    @Override
    public void activityInitData() {
        loading.setVisibility(View.GONE);
        err404.setVisibility(View.GONE);
        if (buyRecordsInfo != null && buyRecordsInfo.getList() != null
                && buyRecordsInfo.getList().size() > 0) {

            mActPurchaseHistoryListview.setVisibility(View.VISIBLE);
            act_purchasehistory_null.setVisibility(View.GONE);

            totalPage = Integer.parseInt(buyRecordsInfo.getTotalPage());

            if (buyRecordsInfo.getList() != null && buyRecordsInfo.getList().size() > 0) {

                List<BuyRecordInfo> templist = buyRecordsInfo.getList();
                if (mBuyRecordInfoListData == null) {
                    mBuyRecordInfoListData = templist;
                } else {
                    mBuyRecordInfoListData.addAll(templist);
                }
                if (adapter == null) {
                    adapter = new PurchaseHistoryAdapter(this);
                    adapter.setmHistoryAdapterListener(this);
                    adapter.setList(mBuyRecordInfoListData);
                    mActPurchaseHistoryListview.setAdapter(adapter);
                } else {
                    adapter.setList(mBuyRecordInfoListData);
                    adapter.notifyDataSetChanged();
                }
                pageIndex++;
                mListFooter.loadingSuccess();
            }
        } else {
            // 购买历史为空
            mActPurchaseHistoryListview.setVisibility(View.GONE);
            act_purchasehistory_null.setVisibility(View.VISIBLE);
            return;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        if (mBuyRecordInfoListData != null && mBuyRecordInfoListData.size() > position) {
            BuyRecordInfo buyRecordInfo = mBuyRecordInfoListData.get(position);
            // 总状态为开
            if ("N".equals(buyRecordInfo.getHide())) {
                // 封面页开
                if ("1".equals(buyRecordInfo.getCr_cover_isopen())) {
                    BookCoverActivity.openBookCover(PurchaseHistoryActivity.this,
                            buyRecordInfo.getBookId());
                } else {
                    // 封面关
                    showMsg(getString(R.string.error_bookswitch_coverisclose));
                    return;
                }
            } else {
                // 总状态位关
                showMsg(getString(R.string.error_bookswitch_ishide));
                return;
            }

        }
    }


    /** 翻页加载请求 */
    private void requestAppList() {
        this.controller.handle(0, this.pageIndex); // 获取app数据
        mListFooter.loadingStart();
    }


    /**
     * 显示无网络提示
     */
    private void show404() {
        err404.setVisibility(View.VISIBLE);
        loading.setVisibility(View.GONE);
        mActPurchaseHistoryListview.setVisibility(View.GONE);
    }

    @Override
    public void request_content_io() {

    }

    @Override
    public void request_reponse_io() {

    }

    @Override
    public void request_parse_io() {

    }

    @Override
    public void request_parse_format() {

    }

    @Override
    public void request_net_error() {

    }

    @Override
    public void request_timeout() {

    }

    @Override
    public void request_url() {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClickDetails(String bid, String chapterTotal) {
        Intent intent = new Intent(this, PayChapterHistoryActivity.class);
        intent.putExtra("bookId", bid);
        intent.putExtra("chapterTotal", chapterTotal);
        ActivityManager.getInstance().startNextActivity(intent, this);
    }
}
